package com.dikeleakagedetection.myapplication.ui.database

import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.RecyclerView
import com.dikeleakagedetection.myapplication.R
import com.dikeleakagedetection.myapplication.logic.dao.Tablet
import com.dikeleakagedetection.myapplication.utils.getImageByFilePath

class TabletAdapter(val context: Fragment, private val tabletList: List<Tablet>) : RecyclerView.Adapter<TabletAdapter.ViewHolder>() {
    class ViewHolder(view: View) : RecyclerView.ViewHolder(view){
        val imgTabletPic = view.findViewById<ImageView>(R.id.img_tablet_pic)
        val tvTabletLocation = view.findViewById<TextView>(R.id.tv_tablet_location)
        val tvTabletDate = view.findViewById<TextView>(R.id.tv_tablet_date_frag_data_monitor)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_tablet_frag_database, parent, false)
        val holder = ViewHolder(view)
        return holder
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val tablet = tabletList[position]
        if(tablet.imgFileUri != null){
            holder.imgTabletPic.setImageBitmap(getImageByFilePath(tablet.imgFileUri!!))
        }
        holder.tvTabletLocation.text = tablet.place
        holder.tvTabletDate.text = "${tablet.date} ${tablet.id}"
        holder.itemView.setOnClickListener {
            val intent = Intent(context.context, TabletActivity::class.java).apply {
                putExtra("tablet_id", tablet.id)
            }
            context.startActivity(intent)
        }
    }

    override fun getItemCount() = tabletList.size
}